﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Web;
using QzgfFrame.Utility.Core.Export;
using System.IO;
using System.Xml;

namespace QzgfFrame.Utility.Core.Import
{
    public class ImportUtil
    {
        protected log4net.ILog Logger = log4net.LogManager.GetLogger("ImportUtil");

        //返回数据集
        public ArrayList Import(HttpPostedFileBase file, String type, String sqlmapid, String path)
        {
            //另存上传文件
            string relpath = SaveFile(file,path);
            //读取sqlmap配置
            Hashtable list = ImportConfig("~/Config/imports.xml");
            var exportInfo = list[sqlmapid] as ExportInfo;
            //读取excel数据信息
            ImportFacade importExc = ImportFactory.GetInstance(type);
            importExc.Init(relpath, exportInfo.GetColumns(), exportInfo.GetFields());
            //读取数据集返回
            ArrayList result=new ArrayList();
            Hashtable line = importExc.readLine();
            while (line != null)
            {
                result.Add(line);
                line = importExc.readLine();
            }
            return result;
        }

        /// <summary>
        /// 上传文件,返回bool类型,判断上传是否成功
        /// </summary>
        /// <param name="newfilename">上传到服务器后的新名称</param>
        /// <param name="file">传递HtmlInputFile对象</param>
        /// <returns></returns>
        public string SaveFile(HttpPostedFileBase file, string path)
        {
            //判断该文件夹是否存在，没有的话就创建
            string filename = Path.GetFileName(file.FileName);
            string strpath = HttpContext.Current.Request.MapPath(path);
            if (!Directory.Exists(strpath))
            {
                Directory.CreateDirectory(strpath);
            }
            string filepath = strpath + filename;
            try
            {
                file.SaveAs(filepath);
            }
            catch { }
            return filepath;
        }


        /// <summary>
        /// 解析导出文件的配置信息，该信息保存于一个xml文件里，格式如
        /// </summary>
        /// <param name="configfile">文件路径</param>
        /// <returns></returns>
        public Hashtable ImportConfig(String configfile)
        {
            Hashtable configList = new Hashtable();
            try
            {
                //这里采用dom4j的xml解析器
                var context = HttpContext.Current;
                var xml = new XmlDocument();
                xml.Load(context.Server.MapPath(configfile));
                //从配置文件里取得所有需要导出的节点信息
                XmlNodeList nodeList = xml.SelectNodes("/imports/import");
                if (nodeList != null)
                {
                    foreach (XmlNode element in nodeList)
                    {
                        //配置信息对应的类
                        var ei = new ExportInfo();
                        ei.SetSqlId(element.Attributes["sqlId"].Value);
                        ei.SetFileName(element.Attributes["filename"].Value);

                        XmlNodeList cols = element.SelectNodes("column");
                        String[] fields = null;
                        String[] columns = null;
                        if (cols.Count > 0)
                        {
                            fields = new String[cols.Count];
                            columns = new String[cols.Count];
                        }

                        for (int i = 0; i < cols.Count; i++)
                        {
                            XmlNode elCol = cols.Item(i);
                            if (elCol != null)
                            {
                                fields[i] = elCol.Attributes["name"].Value;
                                columns[i] = elCol.InnerText;
                            }
                        }
                        ei.SetFields(fields);
                        ei.SetColumns(columns);
                        XmlNode descNode = element.SelectSingleNode("description");
                        if (descNode != null)
                            ei.SetDescription(descNode.InnerText);
                        if (element.Attributes != null) configList.Add(element.Attributes["id"].Value, ei);
                    }
                }
            }
            catch (Exception ex)
            {
                if (Logger.IsInfoEnabled)
                {
                    Logger.Error(ex);
                }
            }
            return configList;

        }

    }
}
